<!--
 * @Author: zjf
 * @Date: 2023-04-20 18:59:22
 * @LastEditors: zjf
 * @LastEditTime: 2023-12-01 16:38:38
 * @Description: 下拉选择
-->
<template>
  <div>
    <el-select :disabled="disabled" v-model="value2" placeholder="请输入关键字" filterable remote clearable
      :remote-method="remoteMethod" @clear="clearData">
      <el-option class="my-option" v-for="item in searchList" :key="item.id" :label="item[labelKey1]" :value="item.id"
        v-loading="loading">
        <b class="name" v-html="item.parseName"></b>
        <span v-if="labelKey2">{{ item[labelKey2] }}</span>
      </el-option>
      <span slot="empty" class="empty-class">
        未找到
        <a v-if="hasAdd" @click="handleAdd">点击新建</a>
      </span>
    </el-select>

    <!--表单-->
    <l-dialog :title="'新增'" :visible.sync="formVisible" :height="400" :width="600" @ok="handleSave"
      @close="handleCloseForm">
      <my-form ref="form" :config="config"></my-form>
    </l-dialog>

  </div>
</template>

<script>
import MyForm from './form'

export default {
  name: "l-remote-select",
  components: {
    MyForm
  },
  props: {
    value: String,
    disabled: {
      type: Boolean,
      default: false,
    },
    labelKey1: {
      type: String,
      default: 'projectName'
    },
    labelKey2: {
      type: String,
      default: ''
    },
    hasAdd: {
      type: Boolean,
      default: false,
    },
    config: Object
  },
  data() {
    return {
      searchList: [],
      loading: false,
      selectedItemId: "",

      formVisible: false,
    };
  },
  computed: {
    value2: {
      get() { // 回调函数
        return this.value
      },
      set(val) { // 监视当前属性值的变化
        const selectedItem = this.searchList.find(option => option.id == val);
        this.$emit('change', selectedItem)
        this.$emit('input', val); // 传递给父组件
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.remoteMethod()
    },
    inputChange(info) {
      this.$emit('change', info)
    },
    clearData() {
      this.remoteMethod()
    },
    handleSelectionChange(selectedItem) {
      this.$emit('input', selectedItem.id);
      this.$emit('change', selectedItem);
    },
    async remoteMethod(keyword) {
      // if (!keyword) {
      //   this.searchList = [];
      //   return;
      // }

      this.loading = true;
      try {
        this.$emit("remoteMethod", keyword, data => {
          this.searchList = this.setHightLight(data, keyword)
        });
      } catch (error) {
        console.error(error);
        this.searchList = [];
      }
      finally {
        this.loading = false;
      }
    },
    setSearchList(data) {
      this.searchList = data ? [data] : [];
    },

    /** 设置高亮 */
    setHightLight(arr = [], keyword) {
      if (arr.length > 0 && keyword) {
        arr = arr.filter((item) => {
          let reg = new RegExp(keyword, "g");
          let replaceString = `<span style="color:#2baf6c;padding:0">${keyword.trim()}</span>`;
          if (item[this.labelKey1].match(reg)) {
            //为了不影响原始name，我们这里给item重新设置一个parseName，模板中显示的是parseName
            item.parseName = item[this.labelKey1].replace(reg, replaceString);
            return item;
          }
        });
        return arr;
      } else {
        return arr.map(t => ({ parseName: t[this.labelKey1], ...t }))
      }
    },

    //#region 新增
    handleAdd() {
      this.formVisible = true
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
      this.formVisible = false
    },
    async handleSave(showLoading, hideLoading) {
      showLoading('保存数据中...')
      if (await this.$refs.form.validateForm()) {
        const res = await this.$refs.form.saveForm()
        if (res) {
          // 将新增成功的项目信息带入选择框中
          this.formData.selectProject = res.projectName;
          this.formData.selectProjectName = '';
          this.newProject = res
          const msg = '新增成功!'
          this.$message({
            type: 'success',
            message: this.$t(msg)
          })
          this.formVisible = false
        }
      }
      hideLoading()
    },
    //#endregion


  }
};
</script>
<style lang="scss" scoped>
.my-option {
  height: auto;
  padding: 5px 20px;
  line-height: 140%;
  .name {
    display: block;
  }
  span {
    font-size: 11px;
  }
}
.empty-class {
  width: 100%;
  height: 39px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>